import 'dart:math';

import 'package:flutter/rendering.dart';
import 'package:lepig/model/ProductModel.dart';
import 'package:lepig/model/SelectProductTypeModel.dart';
import 'package:lepig/request/HttpSelectProducts.dart';
import 'package:lepig/widget/GoodsHorizontalOne.dart';
import 'package:lepig/widget/GoodsHorizontalTwo.dart';
import 'package:lepig/widget/screenTab/ScreenTab.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class OtherPage extends StatefulWidget {
  OtherPage({key, this.list, this.productTypeModel}) : super(key: key);
  List<SelectProductTypeModel> list;
  SelectProductTypeModel productTypeModel;

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _OtherPageState();
  }
}

class _OtherPageState extends State<OtherPage>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  ScrollController scrollController = new ScrollController();

  double categoryHeightOld = 180;
  double categoryHeight = 180;
  List<ProductModel> products = [];
  int page = 1;
  int categoryId = 1;

  //分类搜索
  SelectProductsParams params = new SelectProductsParams();

  //下拉刷新
  bool _isLoding = false;

  //是否加载中
  bool _onLoding = true;
  //是否加载完毕
  bool _onDone =false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    initCategory();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    scrollController.dispose();
  }

  //初始分类数据
  initCategory() {
    if (widget.productTypeModel != null) {
          params.q=widget.productTypeModel.name.toString();
         getSelectProducts();
    }
  }

  //获取分类商品
  getSelectProducts() {
    setState(() {
      this._onLoding = false;
    });
    HttpSelectProducts(context, params: params).then((value) {
      if (mounted) {
        setState(() {
          this._onLoding = true;
          if(value.length==0&&params.pageNum=="1"){
            this._onDone=true;
          }
          products.addAll(value);
        });
      }
    });
  }

  //查询分类
  querySelectProducts(SelectProductTypeModel item) {
    this.categoryId = item.id;

//    if (item.ignoreParentType == 1) {
//      params.cid = widget.productTypeModel.q;
//    }
    if (_onLoding) {
      this.products = [];
      params.q = item.q;
      params.pageNum = "1";
      getSelectProducts();
    }
  }

  //重置
  refrsh() {
    this._onDone = false;
    params = new SelectProductsParams();
    params.q=widget.productTypeModel.name;
    getSelectProducts();
  }

  screenTab() {
    params.pageNum = "1";
    this.products = [];
    getSelectProducts();
  }

  //

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return new Scaffold(
      body: new NotificationListener<ScrollNotification>(
        // ignore: missing_return
        onNotification: (ScrollNotification notification) {
          //到底部小于20 就刷新
          if (notification.metrics.extentAfter < 20 && _onLoding&& !this._onDone) {
                params.pageNum=(int.parse(params.pageNum)+1).toString();
                getSelectProducts();
          }
        },
        child: new RefreshIndicator(
            child: new CustomScrollView(
              slivers: <Widget>[
                SliverToBoxAdapter(
                  child: new Container(
                    child: new Wrap(
                      spacing: 10.0, // 主轴(水平)方向间距
                      runSpacing: 10.0, // 纵轴
                      children: widget.list.map((SelectProductTypeModel item) {
                        return _categoryItem(item.thum, item.name, item.id, () {

                          querySelectProducts(item);

                        });
                      }).toList(),
                    ),
                    color: Colors.white,
                    width: double.infinity,
                    padding: EdgeInsets.all(10.0),
                    margin: EdgeInsets.only(bottom: 10.0),
                    height: categoryHeight,
                  ),
                ),
                SliverPersistentHeader(
                    pinned: true, //是否固定在顶部
                    floating: true,
                    delegate: _SliverAppBarDelegate(
                      minHeight: 50, //收起的高度
                      maxHeight: 50, //展开的最大高度
                      child: new Container(
                        padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
                        color: Colors.white,
                        child: new ScreenTab(onFunction: (s, v) {
                          params.isCoupon = v.toString();
                          params.sort = s;
                          screenTab();
                        }),
                      ),
                    )),
               SliverGrid(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      childAspectRatio: 0.560,
                      crossAxisCount: 2,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 0),
                  delegate: SliverChildBuilderDelegate(
                      (BuildContext context, int index) {
                    return new Padding(
                      padding: EdgeInsets.only(top: 10.0),
                      child: GoodsHorizontalTwo(products[index]),
                    );
                  }, childCount: products.length),
                ),
                new SliverToBoxAdapter(
                  child: new Visibility(
                    child: new Container(
                      padding: EdgeInsets.fromLTRB(0, 10, 0, 10),
                      child: new Center(
                        child: new Text(this._onDone?"没有数据了":"加载中...."),
                      ),
                    ),
                    visible: !_isLoding,
                  ),
                ),
              ],
            ),
            // ignore: missing_return
            onRefresh: () {
              return _refresh();
            }),
      ),
    );
  }

  Future<Null> _refresh() async {
    if (!_onLoding) {
      return null;
    }
    this.refrsh();
  }

  Color color = Colors.redAccent;
  Color color2 = Colors.black45;

  Widget _categoryItem(String src, String name, int id, Function onTab) {
    return new InkWell(
      child: new Container(
        width: MediaQuery.of(context).size.width / 6,
        child: new Column(
          children: <Widget>[
            new ClipOval(
              child: Image.network(
                src,
                width: 50.0,
              ),
            ),
            new SizedBox(
              height: 5.0,
            ),
            new Text(
              name,
              style: TextStyle(
                  color: id == this.categoryId ? color : color2,
                  fontSize: 12.0),
            )
          ],
        ),
      ),
      onTap: onTab,
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => max(maxHeight, minHeight);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}
